package com.jq.jqaicode.ai;

import com.jq.jqaicode.config.RedisChatMemoryStore;
import com.jq.jqaicode.exception.MyInputGuardrail;
import com.jq.jqaicode.service.AiChatHistoryService;
import dev.langchain4j.community.model.dashscope.QwenStreamingChatModel;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.request.ChatRequestParameters;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.service.AiServices;
import jakarta.annotation.Resource;
import org.bsc.langgraph4j.action.NodeAction;
import org.bsc.langgraph4j.langchain4j.generators.StreamingChatGenerator;
import org.bsc.langgraph4j.prebuilt.MessagesState;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.management.MemoryManagerMXBean;
import java.util.Map;

/**
 * ai 服务类工厂
 */
@Configuration
public class AiCodeServiceFactory {

    @Resource
    private ChatModel qwChatModel;
//    @Resource
//    ContentRetriever contentRetriever;
    @Resource
    private AiChatHistoryService aiChatHistoryService;
    @Resource
    private RedisChatMemoryStore redisChatMemoryStore;
    @Resource
    StreamingChatModel qwStreamingChatModel;

    @Bean
    public AiCodeService aiCodeService(){
        //会话记忆
        ChatMemoryProvider chatMemoryProvider = memoryId -> {
            MessageWindowChatMemory chatMemory = MessageWindowChatMemory.builder()
                    .id(memoryId)
                    .chatMemoryStore(redisChatMemoryStore)
                    .maxMessages(20)
                    .build();
            aiChatHistoryService.loadChatHistoryToMemory(String.valueOf(memoryId), chatMemory, 20);
            return chatMemory;
        };

        //构建ai service
        AiCodeService aiCodeService = AiServices.builder(AiCodeService.class)
                .chatModel(qwChatModel)
                .chatMemoryProvider(chatMemoryProvider)//记忆持久化
                .streamingChatModel(qwStreamingChatModel)//流
                .inputGuardrails(new MyInputGuardrail())//护轨
                //.tools(new AiTool())//工具
                //.contentRetriever(contentRetriever)//rag
                .build();

        return aiCodeService;
    }

}
